package main

import "fmt"

func main1() {
	s := make([]int, 3, 5)
	for i := 0; i < 3; i++ {
		s[i] = i + 1
	}
	fmt.Println("s:", s)                    // s = [1, 2, 3]
	fmt.Printf("s[1] address: %p\n", &s[1]) // s[1] address: 0xc0000b6038

	subSlice := s[0:2]
	fmt.Printf("sub slice len:%d, cap:%d\n", len(subSlice), cap(subSlice)) // sub slice len:2, cap:5

	/** 母切片的内存使用完后，子切片再执行append就会申请一块新的内存地址，把老数据拷贝过来，在新内存上执行append操作 */
	subSlice = append(subSlice, 10)
	fmt.Printf("s=%v, subSlice=%v, s[1] address:%p, subSlice[1] address:%p\n", s, subSlice, &s[1], &subSlice[1]) // s=[1 2 10], subSlice=[1 2 10], s[1] address:0xc0000b6038, subSlice[1] address:0xc0000b6038

	subSlice = append(subSlice, 6, 7)
	subSlice[0] = 8
	fmt.Printf("s=%v, subSlice=%v, s[1] address:%p, subSlice[1] address:%p\n", s, subSlice, &s[1], &subSlice[1]) // s=[8 2 10], subSlice=[8 2 10 6 7], s[1] address:0xc0000b6038, subSlice[1] address:0xc0000b6038

	// 验证开辟新的内存后，s和subSlice地址是否不一致
	subSlice = append(subSlice, 100)
	fmt.Printf("s=%v, subSlice=%v, s[1] address:%p, subSlice[1] address:%p\n", s, subSlice, &s[1], &subSlice[1]) // s=[8 2 10], subSlice=[8 2 10 6 7 100], s[1] address:0xc00019a038, subSlice[1] address:0xc0001a4008
}
